import threading
import time

class TimedDict:
    def __init__(self, timeout=60):
        self.data = {}
        self.timeout = timeout
        self.lock = threading.Lock()
        self.start_cleanup()
    
    def set(self, key, value):
        with self.lock:
            self.data[key] = {'value': value, 'time': time.time()}
    
    def get(self, key):
        with self.lock:
            if key in self.data:
                self.data[key]['time'] = time.time()
                return self.data[key]['value']
            return None
    
    def _cleanup(self):
        while True:
            time.sleep(1)
            with self.lock:
                current_time = time.time()
                keys_to_delete = [key for key, val in self.data.items() if current_time - val['time'] > self.timeout]
                for key in keys_to_delete:
                    del self.data[key]
    def del_data(self, key):
        del self.data[key]
    
    def start_cleanup(self):
        thread = threading.Thread(target=self._cleanup, daemon=True)
        thread.start()
if __name__ == "__main__":
    # 使用示例
    timed_dict = TimedDict(timeout=8)  # 设定超时时间为10秒
    # timed_dict.start_cleanup()

    timed_dict.set("key1", "value1")
    time.sleep(5)
    print(timed_dict.get("key1"))  # 输出: value1
    time.sleep(10)
    print(timed_dict.get("key1"))  # 输出: None (因为键值对已经超时被删除)
